package com.outsourcing.bottle.ui;

import java.util.HashMap;

import oauth.facebook.AsyncFacebookRunner;
import oauth.facebook.BaseRequestListener;
import oauth.facebook.DialogError;
import oauth.facebook.Facebook;
import oauth.facebook.Facebook.DialogListener;
import oauth.facebook.FacebookError;
import oauth.facebook.SessionEvents;
import oauth.facebook.SessionEvents.AuthListener;
import oauth.facebook.Util;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

import com.outsourcing.bottle.BasicActivity;
import com.outsourcing.bottle.R;
import com.outsourcing.bottle.db.OtherConfigTable;
import com.outsourcing.bottle.db.PlatformAccountTable;
import com.outsourcing.bottle.domain.OtherConfigEntry;
import com.outsourcing.bottle.domain.PlatformAccount;
import com.outsourcing.bottle.domain.PlatformBindConfig;
import com.outsourcing.bottle.domain.UrlConfig;
import com.outsourcing.bottle.oauth.OAuth;
import com.outsourcing.bottle.util.AppContext;
import com.outsourcing.bottle.util.HttpUtils;
import com.outsourcing.bottle.util.UICore;
/**
 * 
 * @author 06peng
 *
 */
public class LoginPlatformActivity extends BasicActivity implements OnClickListener, Callback {

	private Button twitter;
	private Button facebook;
	private Button weibo;
	private Button tentcent;
	private Button qq;
	private Button renren;
	private Button douban;
	private Button registerBtn;
	private ImageView close;
	private String platform;
	public OAuth oauth;
	public static final String CALLBACKURL = "app:authorize";
	
	public static final int HAS_BIND = 1;
	public static final int NOT_BIND = 2;
	
	private OtherConfigEntry entry;
	private final int oauth_tritter =28;
	private final int oauth_facebook = 29;
	private final int oauth_weibo = 30;
	private final int oauth_tencent = 31;
	private final int oauth_renren = 32;
	private final int oauth_douban = 33;
	private final int oauth_qq = 34;
	
	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;
	private SessionListener mSessionListener = new SessionListener();
	
	private int regsiterEnable;
	private Handler handler;
	
	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		handler = new Handler(this);
		setContentView(R.layout.login_platform);
		try {
			initWidget();
			OtherConfigTable ot = new OtherConfigTable();
			entry = ot.getBottleOtherConfig();
			regsiterEnable = entry.getRegister_enable();
			if (regsiterEnable == 1) {
				registerBtn.setVisibility(View.VISIBLE);
			} else {
				registerBtn.setVisibility(View.GONE);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private void initWidget() {
		twitter = (Button) findViewById(R.id.login_twitter);
		twitter.setOnClickListener(this);
		
		facebook = (Button) findViewById(R.id.login_facebook);
		facebook.setOnClickListener(this);
		
		weibo = (Button) findViewById(R.id.login_weibo);
		weibo.setOnClickListener(this);
		
		tentcent = (Button) findViewById(R.id.login_tqq);
		tentcent.setOnClickListener(this);
		
		qq = (Button) findViewById(R.id.login_qq);
		qq.setOnClickListener(this);
		
		renren = (Button) findViewById(R.id.login_renren);
		renren.setOnClickListener(this);
		
		douban = (Button) findViewById(R.id.login_douban);
		douban.setOnClickListener(this);
		
		close = (ImageView) findViewById(R.id.close);
		close.setOnClickListener(this);
		
		registerBtn = (Button) findViewById(R.id.login_register);
		registerBtn.setOnClickListener(this);
	}
	
	@Override
	public void onClick(View v) {
		if (v == twitter) {
			if (entry.getTwitter_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			UICore.eventTask(this, this, oauth_tritter, "", null);
		} else if (v == facebook) {
			if (entry.getFacebook_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			platform = PlatformBindConfig.Facebook;
			mFacebook = new Facebook(PlatformBindConfig.Facebook_AppID);
			mAsyncRunner = new AsyncFacebookRunner(mFacebook);
			SessionEvents.addAuthListener(new SampleAuthListener());
			SessionEvents.addAuthListener(mSessionListener);
			mFacebook.authorize((BasicActivity) AppContext.getContext(), new String[] {}, new LoginDialogListener());
		} else if (v == weibo) {
			if (entry.getWeibo_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			UICore.eventTask(this, this, oauth_weibo, "", null);
		} else if (v == tentcent) {
			if (entry.getTencent_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			UICore.eventTask(this, this, oauth_tencent, "", null);
		} else if (v == qq) {
			if (entry.getQq_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			UICore.eventTask(this, this, oauth_qq, "", null);
		} else if (v == renren) {
			if (entry.getRenren_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			UICore.eventTask(this, this, oauth_renren, "", null);
		} else if (v == douban) {
			if (entry.getDouban_enable() == 0) {
				onToast(getString(R.string.platform_error));
				return;
			}
			UICore.eventTask(this, this, oauth_douban, "", null);
		} else if (v == close) {
			finish();
		} else if (v == registerBtn) {
			Intent register = new Intent(LoginPlatformActivity.this, BindRegisterActivity.class);
			startActivity(register);
			LoginPlatformActivity.this.finish();
		}
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (OAuth.reciver != null) {
			unregisterReceiver(OAuth.reciver);
		}
	}
	
	@Override
	public void execute(int mes, Object obj) {
		switch (mes) {
		case oauth_douban:
			platform = PlatformBindConfig.Douban;
			oauth = new OAuth(this, handler, platform, PlatformBindConfig.Douban_AppKey,
					PlatformBindConfig.Douban_AppSecret);
			oauth.requestAccessToken(CALLBACKURL, PlatformBindConfig.Douban_Request_Token,
					PlatformBindConfig.Douban_Access_Token, PlatformBindConfig.Douban_Authorize);
			break;
		case oauth_facebook:
			PlatformAccount account = (PlatformAccount) obj;
			checkBind(account);
			break;
		case oauth_qq:
			platform = PlatformBindConfig.QQ;
			oauth = new OAuth(this, handler, platform);
			oauth.requestAccessTokenForOAuth2(PlatformBindConfig.QQ_Authorize);
			break;
		case oauth_renren:
			platform = PlatformBindConfig.Renren;
			oauth = new OAuth(this, handler, platform);
			oauth.requestAccessTokenForOAuth2(PlatformBindConfig.Renren_Authorize);
			break;
		case oauth_tencent:
			platform = PlatformBindConfig.Tencent;
			oauth = new OAuth(this, handler, platform);
			oauth.requestAccessTokenForOAuth2(PlatformBindConfig.Tencent_Authorize_2);
			break;
		case oauth_tritter:
			platform = PlatformBindConfig.Twitter;
			oauth = new OAuth(this, handler, PlatformBindConfig.Twitter,
					PlatformBindConfig.Twitter_ConsumerKey, PlatformBindConfig.Twitter_ConsumerSecret);
			oauth.requestAcccessTokenForTwitter();
			break;
		case oauth_weibo:
			platform = PlatformBindConfig.Sina;
			oauth = new OAuth(this, handler, platform);
			oauth.requestAccessTokenForOAuth2(PlatformBindConfig.Sina_Authorize2);
			break;
		default:
			break;
		}
	}
	
	public class SampleAuthListener implements AuthListener {

		public void onAuthSucceed() {
			System.out.println("You have logged in! ");
		}

		public void onAuthFail(String error) {
			System.out.println("Login Failed: " + error);
		}
	}

	public class SampleRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				PlatformAccount account = new PlatformAccount();
				Log.d("Facebook-Example", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				account.setAccessToken(mFacebook.getAccessToken());
				if (json.has("name")) {
					account.setNickName(json.getString("name"));
				}
				account.setOpenAvatar("https://graph.facebook.com/"+json.getString("id")+"/picture?type=large");
				account.setOpenExpire(String.valueOf(mFacebook.getAccessExpires()));
				account.setOpenType(6);
				account.setOpenUid(json.getString("id"));
				PlatformAccountTable paTable = new PlatformAccountTable();
				paTable.save(account);
				if (account.getOpenUid() != null && !account.getOpenUid().equals("")) {
					Message msg = Message.obtain(handler, oauth_facebook, account);
					handler.sendMessage(msg);
				}
			} catch (JSONException e) {
				e.printStackTrace();
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
		}
	}

	private final class LoginDialogListener implements DialogListener {
        public void onComplete(Bundle values) {
            SessionEvents.onLoginSuccess();
        }

        public void onFacebookError(FacebookError error) {
            SessionEvents.onLoginError(error.getMessage());
        }
        
        public void onError(DialogError error) {
            SessionEvents.onLoginError(error.getMessage());
        }

        public void onCancel() {
            SessionEvents.onLoginError("Action Canceled");
        }
    }
	
	private class SessionListener implements AuthListener {
        
        public void onAuthSucceed() {
            mAsyncRunner.request("me", new SampleRequestListener());
        }
        
        public void onAuthFail(String error) {
        	
        }
    }
	
	private void checkBind(PlatformAccount account) {
		String url = UrlConfig.check_bind;
		HashMap<String, String> paramsMap = new HashMap<String, String>();
		paramsMap.put("login_uid", String.valueOf(AppContext.getInstance().getLogin_uid()));
		paramsMap.put("login_token", AppContext.getInstance().getLogin_token());
		paramsMap.put("open_type", String.valueOf(account.getOpenType()));
		paramsMap.put("access_token", account.getAccessToken());
		paramsMap.put("token_secret", account.getTokenSecret());
		paramsMap.put("nickname", account.getNickName());
		paramsMap.put("open_uid", account.getOpenUid());
		paramsMap.put("open_sex", String.valueOf(account.getOpenSex()));
		paramsMap.put("open_expire", account.getOpenExpire());
		paramsMap.put("open_avatar", account.getOpenAvatar());
		paramsMap.put("device_token", AppContext.getInstance().getDeviceId());
		try {
			String result = HttpUtils.doPost(this, url, paramsMap);
			JSONObject object = new JSONObject(result);
			if (object.has("results")) {
				final JSONObject resultObj = object.getJSONObject("results");
				System.out.println(resultObj);
				int isbind = resultObj.getInt("isbind");
				if (isbind == 0) {
					if (handler != null) {
						Message message = Message.obtain(handler, LoginPlatformActivity.NOT_BIND, account);
						handler.sendMessage(message);
					}
				} else {
					int login_uid = resultObj.getInt("login_uid");
					String login_token = resultObj.getString("login_token");
					SharedPreferences preferences = LoginPlatformActivity.this.getSharedPreferences("Preferences_userinfo", Activity.MODE_APPEND);
					Editor editor = preferences.edit();
					editor.putInt("login_uid", login_uid);
					editor.putString("login_token", login_token);
					editor.commit();
					AppContext.getInstance().setLogin_token(login_token);
					AppContext.getInstance().setLogin_uid(login_uid);
					if (handler != null) {
						handler.sendEmptyMessage(LoginPlatformActivity.HAS_BIND);
					}
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case HAS_BIND:
			AppContext.getInstance().setOAUTH_TYPE(-1);
			Intent intent = new Intent(LoginPlatformActivity.this, HomeActivity.class);
			startActivity(intent);
			LoginPlatformActivity.this.finish();
			break;
		case NOT_BIND:
			Intent register = new Intent(LoginPlatformActivity.this, BindRegisterActivity.class);
			register.putExtra("platform", platform);
			register.putExtra("openuid", msg.obj.toString());
			startActivity(register);
			LoginPlatformActivity.this.finish();
			break;
		case oauth_facebook:
			PlatformAccount account = (PlatformAccount) msg.obj;
			UICore.eventTask(LoginPlatformActivity.this, LoginPlatformActivity.this, oauth_facebook, "", account);
			break;
		case AppContext.oauth_bind:
			AppContext.getInstance().setOAUTH_TYPE(-1);
			Intent intent2 = new Intent(LoginPlatformActivity.this, HomeActivity.class);
			startActivity(intent2);
			LoginPlatformActivity.this.finish();
			break;
		default:
			break;
		}
		destroyDialog();
		return false;
	}
}
